﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using System.Configuration;
using NLog;
using System.IO;

namespace Gollie.Administration.Service.Tasks
{
	public class OldLogFiles : IAdministrationTask
	{
		private static readonly Logger logger = LogManager.GetCurrentClassLogger();

		CancellationToken ct;

		TaskProperties taskProperties;

		public void Run(CancellationToken ct, TaskProperties properties)
		{
			this.ct = ct;

			this.taskProperties = properties;

			try
			{
				logger.Info("Deleting old logfiles...");

				this.DeleteOldLogFiles();

				logger.Info("Deleting old logfiles finished.");
			}
			catch (Exception e)
			{
				logger.FatalException("Delete old logfiles failed: {0}", e);
			}
		}

		private void DeleteOldLogFiles()
		{
			string logPath = ConfigurationManager.AppSettings["logpath"];
			int expirationInDays = System.Xml.XmlConvert.ToInt32(ConfigurationManager.AppSettings["logexpirationdays"]);

			string[] logPaths = logPath.Split('|');
			foreach (string path in logPaths)
			{
				AdministrationService.DeleteOldFiles(path, "*.log", expirationInDays, logger);
				//this.DeleteOldLogFiles(path, expirationInDays);
			}
		}

		/*
		private void DeleteOldLogFiles(string logPath, int epirationInDays)
		{
			string[] files = Directory.GetFiles(logPath, "*.log", SearchOption.TopDirectoryOnly);

			DateTime limit = DateTime.Now.AddDays(-epirationInDays);

			foreach (string file in files.Where(f => File.GetCreationTime(f) < limit))
			{
				logger.Info("Deleting {0}", file);
				File.Delete(file);
			}
		}
		 */
	}
}
